//
//  JXEmojiView.m
//  Emoji_keyboard
//
//  Created by raymond on 16/4/18.
//  Copyright © 2016年 raymond. All rights reserved.
//

#import "JXEmojiView.h"
#import "JXEmoji.h"
#import "JXEmojiViewLayout.h"

#define BaseItemTag 1000

#define JXEmojiViewCellReuseIdentify @"JXEmojiViewCellReuseIdentify"

#define randomColor                                                            \
  [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0)               \
                  green:((float)arc4random_uniform(256) / 255.0)               \
                   blue:((float)arc4random_uniform(256) / 255.0)               \
                  alpha:1.0]

// emojiCell
@interface JXEmojiViewCell : UICollectionViewCell

@property (nonatomic, strong) JXEmoji *emoji;
@property (nonatomic, strong) UIButton *emojiButton;

@end

@implementation JXEmojiViewCell

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self loadSubviews];
        self.userInteractionEnabled = YES;
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self loadSubviews];
        self.userInteractionEnabled = YES;
    }
    return self;
}

- (void)loadSubviews {
    [self.contentView addSubview:self.emojiButton];
    self.emojiButton.frame = CGRectInset(self.bounds, 3, 3);
//    self.emojiButton.backgroundColor = randomColor;
}

- (void)setEmoji:(JXEmoji *)emoji {
    _emoji = emoji;
    UIImage *image = [UIImage imageWithContentsOfFile:emoji.pngPath];
    [self.emojiButton setImage:image forState:UIControlStateNormal];
}

- (UIButton *)emojiButton {
    if (_emojiButton == nil) {
        _emojiButton = [[UIButton alloc] init];
        _emojiButton.userInteractionEnabled = NO;
    }
    return _emojiButton;
}

@end


// 表情键盘
@interface JXEmojiView () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) JXEmojiViewLayout *layout; // 布局
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIToolbar *toolBar;
@property (nonatomic, strong) NSArray *emojiArr;

@end

@implementation JXEmojiView

- (instancetype)initWithFrame:(CGRect)frame {
  if (self = [super initWithFrame:frame]) {
    [self loadSubviews];
      // 一定要加这段代码系统才会设置大小
    self.translatesAutoresizingMaskIntoConstraints = NO;
      self.autoresizesSubviews = NO;
  }
  return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
  if (self = [super initWithCoder:aDecoder]) {
    [self loadSubviews];
    self.translatesAutoresizingMaskIntoConstraints = NO;
      self.autoresizesSubviews = NO;
  }
  return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
}

- (void)loadSubviews {
    [self addSubview:self.collectionView];
    [self addSubview:self.toolBar];

    NSDictionary *dict = @{ @"cv" : self.collectionView, @"tb" : self.toolBar };
    // 垂直方向
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:
                                                 @"V:|-0-[cv]-0-[tb(44)]-0-|"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:dict]];
    // 水平方向
    [self addConstraints:[NSLayoutConstraint
                             constraintsWithVisualFormat:@"H:|-0-[cv]-0-|"
                                                 options:0
                                                 metrics:nil
                                                   views:dict]];
    [self addConstraints:[NSLayoutConstraint
                             constraintsWithVisualFormat:@"H:|-0-[tb]-0-|"
                                                 options:0
                                                 metrics:nil
                                                   views:dict]];

    // 配置collectionView
    [self setupCollectionView];
    // 配置toolbar
    [self setupToolBar];
}

- (void)setupCollectionView {
  self.collectionView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.f];
  [self.collectionView registerClass:[JXEmojiViewCell class]
          forCellWithReuseIdentifier:JXEmojiViewCellReuseIdentify];
  self.collectionView.pagingEnabled = YES;
}

- (void)setupToolBar {
    self.toolBar.backgroundColor = [UIColor redColor];
}

- (void)itemAction:(UIBarButtonItem *)sender {
    NSIndexPath *indxPath = [NSIndexPath indexPathForItem:0 inSection:sender.tag - BaseItemTag];
    [self.collectionView scrollToItemAtIndexPath:indxPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.emojiArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    JXEmojiPackage *package = self.emojiArr[section];
    return package.emoticons.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  JXEmojiViewCell *cell = [collectionView
      dequeueReusableCellWithReuseIdentifier:JXEmojiViewCellReuseIdentify
                                forIndexPath:indexPath];
    JXEmojiPackage *package = self.emojiArr[indexPath.section];
  JXEmoji *emoji = package.emoticons[indexPath.item];
  cell.emoji = emoji;
  return cell;
}

#pragma mark - UiCollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    JXEmojiPackage *package = self.emojiArr[indexPath.section];
    JXEmoji *emoji = package.emoticons[indexPath.row];
    NSLog(@"emoji:%@, indexPath:%@", emoji.id, indexPath);
}

#pragma mark - getter

- (UICollectionView *)collectionView {
  if (_collectionView == nil) {
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero
                                         collectionViewLayout:self.layout];
    _collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    _collectionView.bounces = NO;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.showsHorizontalScrollIndicator = NO;
  }
  return _collectionView;
}

- (UIToolbar *)toolBar {
  if (_toolBar == nil) {
    _toolBar = [[UIToolbar alloc] init];
    _toolBar.tintColor = [UIColor darkGrayColor];
    NSMutableArray *items = [NSMutableArray array];
    int i = 0;
    NSArray *titles = @[ @"默认", @"QQ" ];
    for (NSString *title in titles) {
      UIBarButtonItem *item =
          [[UIBarButtonItem alloc] initWithTitle:title
                                           style:UIBarButtonItemStylePlain
                                          target:self
                                          action:@selector(itemAction:)];
      item.tag = BaseItemTag + i;
      [items addObject:item];

      i++;
    }
    UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc]
        initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                             target:nil
                             action:nil];
    [items addObject:flexibleItem];
    _toolBar.items = items;
    _toolBar.translatesAutoresizingMaskIntoConstraints = NO;
  }
  return _toolBar;
}

- (JXEmojiViewLayout *)layout {
    if (_layout == nil) {
        _layout = [[JXEmojiViewLayout alloc] init];
    }
    return _layout;
}

- (NSArray *)emojiArr {
    if (_emojiArr == nil) {
        _emojiArr = [JXEmojiPackage packages];
    }
    return _emojiArr;
}

@end
